/**
 * 本地存储工具
 * 提供类型安全的本地存储操作
 */

const PREFIX = 'USER_SYSTEM_'

export enum StorageKey {
  TOKEN = 'TOKEN',
  USER_INFO = 'USER_INFO',
  REMEMBER_ME = 'REMEMBER_ME',
}

class Storage {
  /**
   * 设置存储项
   */
  set<T>(key: StorageKey, value: T): void {
    try {
      const serializedValue = JSON.stringify(value)
      localStorage.setItem(PREFIX + key, serializedValue)
    } catch (error) {
      console.error(`Error setting localStorage key "${key}":`, error)
    }
  }

  /**
   * 获取存储项
   */
  get<T>(key: StorageKey): T | null {
    try {
      const item = localStorage.getItem(PREFIX + key)
      return item ? JSON.parse(item) : null
    } catch (error) {
      console.error(`Error getting localStorage key "${key}":`, error)
      return null
    }
  }

  /**
   * 移除存储项
   */
  remove(key: StorageKey): void {
    try {
      localStorage.removeItem(PREFIX + key)
    } catch (error) {
      console.error(`Error removing localStorage key "${key}":`, error)
    }
  }

  /**
   * 清空所有存储项
   */
  clear(): void {
    try {
      Object.values(StorageKey).forEach((key) => {
        localStorage.removeItem(PREFIX + key)
      })
    } catch (error) {
      console.error('Error clearing localStorage:', error)
    }
  }

  /**
   * 检查存储项是否存在
   */
  has(key: StorageKey): boolean {
    return localStorage.getItem(PREFIX + key) !== null
  }
}

export const storage = new Storage()
